
var barChart = null;
var ctx = null;
var myChart = null;
/**
 * 画用户之间的相似度关系图
 */
Ext.onReady(function() {
	
	ctx = document.getElementById("log");
	//需要在页面加载完成之后实例化此barChart实例

	// drawRelationChart('二狗子', []);
	var calculatedResponseText = '';
//	monitorClicking();
//	drawClickRecord();

	Ext.Ajax.request({

		url : 'servlet/userRelatedRecommend',
		async : true,
		success : function(response) {

			calculatedResponseText = response.responseText;

			calculatedJsonText = JSON.parse(calculatedResponseText);
			var currUserId = calculatedJsonText.currUserId;
			var currUserName = calculatedJsonText.currUserName;
			var historySteps = calculatedJsonText.historySteps;
			var relatedUsers = calculatedJsonText.relatedUsers;
			var recommendedSpots = calculatedJsonText.recommendedSpots;

			// 需要请求数据
			drawFootPrint(historySteps);
//			drawRelationChart(currUserName, relatedUsers);
			
			
//			drawTopClickingBarChart();	
//			drawTopClickingBarChart();
			drawRelation(currUserName,relatedUsers);
			showPersonalRecommendSpots(recommendedSpots);
			monitorClicking();
			drawClickRecord();
			

			// console.log(jsonText);
		},
		failure : function(response) {
			console.log("0000" + response.responseText);

		}

	});

	/*	
	 * calculatedJsonText = JSON.parse(calculatedResponseText); var currUserId =
	 * calculatedJsonText.currUserId; var currUserName =
	 * calculatedJsonText.currUserName; var historySteps =
	 * calculatedJsonText.historySteps; var relatedUsers =
	 * calculatedJsonText.relatedUsers; var recommendedSpots =
	 * calculatedJsonText.recommendedSpots; // 需要请求数据
	 * drawFootPrint(historySteps); drawRelationChart(currUserName,
	 * relatedUsers);
	 */

});

function showPersonalRecommendSpots(recommendedSpots) {

	// var personalRecommendUl1 =
	// document.getElementById("personalRecommendUl1");
	// var personalRecommendDiv =
	// document.getElementById("personalRecommendDiv");
	// var personalRecommendUl1_li =
	// document.getElementById("personalRecommendUl1_li");
	var personalRecommendUl22 = document
			.getElementById("personalRecommendUl22");
	var personalRecommendUl23 = document
			.getElementById("personalRecommendUl23");
/*	var personalRecommendUl1_li_ul1 = document
			.getElementById("personalRecommendUl1_li_ul1");
	var personalRecommendUl1_li_ul2 = document
			.getElementById("personalRecommendUl1_li_ul2");*/

	personalRecommendUl22.innerHTML = '';
	personalRecommendUl23.innerHTML = '';
/*	personalRecommendUl1_li_ul1.innerHTML = '';
	personalRecommendUl1_li_ul2.innerHTML = '';*/

	for (var i = 0; i < recommendedSpots.length; i++) {
		// for(var i=0;i<recommendedSpots.length;i++){

		/*
		 * if(i<3){//第一行显示的3个景点
		 * 
		 * var elemLi = document.createElement('li'); var elemA =
		 * document.createElement('a'); var elemImg =
		 * document.createElement('img'); var elemH =
		 * document.createElement('h'); elemH.className = 'title';
		 * elemH.innerHTML = recommendedSpots[i].spotName; elemImg.src =
		 * 'image/default.jpg'; elemImg.alt = recommendedSpots[i].spotName;
		 * elemA.href = '#' + recommendedSpots[i].spotName;
		 * elemA.appendChild(elemImg); elemA.appendChild(elemH);
		 * elemLi.appendChild(elemA);
		 * personalRecommendUl1_li_ul1.appendChild(elemLi); }else if(3 <= i && i <
		 * 6){
		 * 
		 * var elemLi = document.createElement('li'); var elemA =
		 * document.createElement('a'); var elemImg =
		 * document.createElement('img'); var elemH =
		 * document.createElement('h'); elemH.className = 'title';
		 * elemH.innerHTML = recommendedSpots[i].spotName; elemImg.src =
		 * 'image/default.jpg'; elemImg.alt = recommendedSpots[i].spotName;
		 * elemA.href = '#' + recommendedSpots[i].spotName;
		 * elemA.appendChild(elemImg); elemA.appendChild(elemH);
		 * elemLi.appendChild(elemA);
		 * personalRecommendUl1_li_ul2.appendChild(elemLi);
		 */
		if (i < 4) {

			var elemLi = document.createElement('li');

			elemLi.width = '25%';
			var elemA = document.createElement('a');
			var elemImg = document.createElement('img');
			var elemH = document.createElement('h3');
			elemA.className = 'clickSpotClass monitored';
			elemH.className = 'title';
			elemH.innerHTML = recommendedSpots[i].spotName;
			elemImg.src = 'image/default1.jpg';
			elemImg.alt = recommendedSpots[i].spotName;
			elemA.href = 'mapPages/index_left.jsp?loc=' + recommendedSpots[i].spotName;
			elemA.appendChild(elemImg);
			elemA.appendChild(elemH);
			elemLi.appendChild(elemA);
			personalRecommendUl22.appendChild(elemLi);
		} else if(i<8) {

			var elemLi = document.createElement('li');

			elemLi.width = '25%';
			var elemA = document.createElement('a');
			var elemImg = document.createElement('img');
			var elemH = document.createElement('h3');
			elemA.className = 'clickSpotClass monitored';
			elemH.className = 'title';
			elemH.innerHTML = recommendedSpots[i].spotName;
			elemImg.src = 'image/default1.jpg';
			elemImg.alt = recommendedSpots[i].spotName;
			elemA.href = 'mapPages/index_left.jsp?loc=' + recommendedSpots[i].spotName;
			elemA.appendChild(elemImg);
			elemA.appendChild(elemH);
			elemLi.appendChild(elemA);
			personalRecommendUl23.appendChild(elemLi);

		}

	}

}
/**
 * 画脚丫记录足迹
 */
function drawFootPrint(historySteps) {

	// <!-- <li><p><a href="#"
	// title='景点1'>2010.01.02</a></p><p>&nbsp;</p><p>&nbsp;</p></li>//创建类似此格式的html内容
	var appendedHtml = '';
	for (var i = 0; i < historySteps.length; i++) {

		if (i % 2 == 0) {
			var currHtml = "<li><a class='monitored' href='mapPages/index_left.jsp?loc=" +historySteps[i].spotName + "' title="
					+ historySteps[i].travelTime + "><h3>"
					+ historySteps[i].spotName
					+ "</h3></a><p>&nbsp;</p><p>&nbsp;</p></li>";
			appendedHtml += currHtml;
		} else {
			var currHtml = "<li><p>&nbsp;</p>	<a class='monitored' href='mapPages/index_left.jsp?loc=" +historySteps[i].spotName + "' title="
					+ historySteps[i].travelTime + "><h3>"
					+ historySteps[i].spotName + "</h3></a><p>&nbsp;</p></li>";
			appendedHtml += currHtml;
		}

	}

	var elemUl1 = document.getElementById('dates');
	elemUl1.innerHTML = appendedHtml;
	/*
	 * var footDiv = document.getElementById("footDiv"); for(var i=0;i<historySteps.length;i++){
	 * 
	 * if(i%2 == 0){
	 * 
	 * var elemUl1 = document.getElementById('footul1');
	 * 
	 * var elemLi1 = document.createElement('li');
	 * 
	 * var elemImg = document.createElement('img'); elemImg.className = 'ouImg';
	 * elemImg.src = './image/foot1.bmp'; elemLi1.appendChild(elemImg);
	 * elemUl1.appendChild(elemLi1);
	 * 
	 * }else{
	 * 
	 * var elemUl1 = document.getElementById('footul1');
	 * 
	 * var elemLi1 = document.createElement('li');
	 * 
	 * var elemImg = document.createElement('img'); elemImg.src =
	 * './image/foot2.bmp'; elemImg.className = 'jiImg';
	 * elemLi1.appendChild(elemImg); elemUl1.appendChild(elemLi1); } }
	 */
}
function drawRelationChart(currUserName, related10Users) {

	// 解析参数

	var userNames = new Array();
	var userSims = new Array();

	if (!(related10Users == null || related10Users <= 0)) {

		for (var i = 0; i < related10Users.length; i++) {

			userNames.push(related10Users[i].userName);
			userSims.push(related10Users[i].userSim);
		}
	} else {

		userNames = [ "用啊啊啊啊啊啊啊户1", "用户啊啊啊啊啊啊啊啊啊2", "用啊啊啊啊啊啊啊啊户3",
				"用户啊啊啊啊啊啊啊4", "用啊啊啊啊啊户5", "用户6啊啊啊啊啊", "用啊啊啊啊啊啊啊户7",
				"用啊啊啊啊啊啊啊户8", "用户9", "用户10" ];
		userSims = [ 0.95, 0.90, 0.75, 0.74, 0.80, 0.66, 0.60, 0.78, 0.33, 0.5 ];

	}

	var ctx = document.getElementById("graph1_canvas");
	var data = {
		labels : userNames,
		// labels: ["用户1", "用户2", "用户3", "用户4", "用户5", "用户6",
		// "用户7","用户8","用户9","用户10"],
		datasets : [ {
			label : "兴趣偏好相似度",
			backgroundColor : "rgba(255,99,132,0.2)",
			borderColor : "rgba(255,99,132,1)",
			pointBackgroundColor : "rgba(255,99,132,1)",
			pointBorderColor : "#fff",
			pointHoverBackgroundColor : "#fff",
			pointHoverBorderColor : "rgba(255,99,132,1)",
			data : userSims
		// data : [ 0.95, 0.90, 0.75, 0.74, 0.80, 0.66, 0.60, 0.78, 0.33, 0.5 ]
		} ]
	};

	new Chart(ctx, {
		type : "radar",
		data : data,
		options : {

			// defaultFontSize:20,
			fontColor : 'rgb(44, 44, 44)',
			// fontSize:20,
			// fullWidth : true

			scale : {
				reverse : false,
				ticks : {
					beginAtZero : true
				}
			}

		}
	});
}

/**
 * 记录用户点击事件，保存cookie,还考虑重绘统计柱状图
 */
function monitorClicking(){
	
/**
 * 给document增加点击事件监听
 */
	
	/* $("a").find("h3").on("click",function(){
		
		var clickedLoc = $(this).find()text();
		alert('测试是否唤起...' + clickedLoc);
		$("#log").html("当前用户点击次数为：" + globalIVal + "~~~用户当前点击的内容为：" + clickedLoc);
	}); */
//	$("a").attr("cID",generateUUID());+
	
	$("a.monitored h3").on("click",function(){
		$("a").attr("href","javascript:void(0)");
		var clickedLoc = $(this).text();
		var clickedLocPinyin = pinyin.getFullChars(clickedLoc);
//		alert('测试是否唤起...' + clickedLoc);
//		$("#log").html("当前用户点击次数为：0~~~用户当前点击的内容为：" + clickedLoc);
		//创建cookie保存某个景点被点击了多少次，该记录在一次浏览中有效，关闭所有浏览器标签页则失效。采用
		
		setCookie(clickedLoc);
		drawClickRecord();
		window.setTimeout("window.location = 'mapPages/index_left.jsp?loc="+clickedLoc+"'",1000);
	});
}

/**
 * 生成唯一id
 */
function generateUUID() {
	var d = new Date().getTime();
	var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	  var r = (d + Math.random()*16)%16 | 0;
	  d = Math.floor(d/16);
	  return (c=='x' ? r : (r&0x3|0x8)).toString(16);
	});
	return uuid;
	};
	
/**
 * 获取指定名称的cookie的value
 */
function getCookie(c_name)
{
	var cookieContent = unescape(document.cookie);
//	alert("getted cookies:" + cookieContent);
if (cookieContent.length>0)
  {
  c_start=cookieContent.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
	    c_start=c_start + c_name.length+1; 
	    c_end=cookieContent.indexOf(";",c_start);
	    if (c_end==-1) c_end=cookieContent.length;
	    return parseInt(unescape(cookieContent.substring(c_start,c_end)));
    } 
  }
return 0;
}


/**
 * 画用户点击记录统计图，显示用户点击top10
 */
/*function drawTopClickingBarChart(){
	var topClickedSpots = getTopClickedCookies();
	var topClickedSpotsLabel = new Array();
	var topClickedSpotsTimes = new Array();
	if(topClickedSpots == null || topClickedSpots.length<1){
		return false;
	}else{
		for(var i=0;i<topClickedSpots.length;i++){
			topClickedSpotsLabel[i] = topClickedSpots[i].spotName;
			topClickedSpotsTimes[i] = topClickedSpots[i].clickRecords;
			
			
		}
	}
	
	var ctx = document.getElementById("log");
	var data = {
		    labels: topClickedSpotsLabel,
		    datasets: [
		        {
		            label: "浏览次数",
		            backgroundColor: [
		                'rgba(255, 99, 132, 0.2)',
		                'rgba(54, 162, 235, 0.2)',
		                'rgba(255, 206, 86, 0.2)',
		                'rgba(75, 192, 192, 0.2)',
		                'rgba(153, 102, 255, 0.2)',
		                'rgba(255, 159, 64, 0.2)'
		            ],
		            borderColor: [
		                'rgba(255,99,132,1)',
		                'rgba(54, 162, 235, 1)',
		                'rgba(255, 206, 86, 1)',
		                'rgba(75, 192, 192, 1)',
		                'rgba(153, 102, 255, 1)',
		                'rgba(255, 159, 64, 1)'
		            ],
		            borderWidth: 1,
		            data: topClickedSpotsTimes,
		        }
		    ]
		};
	new Chart(ctx, {
	    type: "bar",
	    data: data,
	    options: {
	    	padding:0,
	        scales: {
	            xAxes: [{
	                stacked: true
	            }],
	            yAxes: [{
	                stacked: true
	            }]
	        }
	    }
	});
	
}*/
/**
 * 获取用户点击最多的景点
 */
function getTopClickedCookies(){
	
	var clickedSpotArr = new Array();
	if(document.cookie.length > 0){
		
		var cookieBody = document.cookie;
		clickedLocsInfo = cookieBody.split(";");
		
		for(var i=0;i<clickedLocsInfo.length;i++){
			
			var trimedStr = $.trim(clickedLocsInfo[i]);
			var startSub = trimedStr.substring(0,5);
			if(startSub == 'spot_'){//筛选属于景点点击cookie,坑爹呢，cookie从第二个键值对会在前一个；后多一个空格。cccccc
				var subStrArray = trimedStr.split("=");
				
				var clickedSpotEntity = {'spotName':unescape(subStrArray[0]),'clickRecords':parseInt(subStrArray[1])};
				clickedSpotArr.push(clickedSpotEntity);
			}
		}
		clickedSpotArr.sort(compare('clickRecords',false));
//		alert("排序之后的数组长度为：" + clickedSpotArr.length);
//		alert("排序之后的数组为：" + JSON.stringify(clickedSpotArr));
		
		/*alert(clickedLocsInfo.length);
		alert("dsfdddd" + clickedLocsInfo);*/
//		alert(clickedLocsInfo.length);
//		alert("dsfdddd" + clickedLocsInfo);
		
		//如果用户点击的景点超过8个，则取前八，否则，取整个点击记录
		if(clickedSpotArr.length > 8){
			
			return clickedSpotArr.slice(0,8);
		}else{
			
			return clickedSpotArr;
		}
		
	}
		
}
/**
 * 用于排序的比较函数
 * @param attr 排序依据的对象属性名
 * @param rev true表示升序排列，false降序排序
 */
function compare(attr,rev){
	
	 if(rev ==  undefined){
         rev = 1;
     }else{
         rev = (rev) ? 1 : -1;
     }
     
     return function(a,b){
         a = a[attr];
         b = b[attr];
         if(a < b){
             return rev * -1;
         }
         if(a > b){
             return rev * 1;
         }
         return 0;
     }
}

/**
 * 设置cookie，设置内容为用户点击的组件内容的次数
 */
function setCookie(clickedLoc)
{
	var spot_clickedLoc = "spot_" + escape(clickedLoc);
//var exdate=new Date()
//exdate.setDate(exdate.getDate()+expiredays)
	var cookieValue=getCookie(spot_clickedLoc);
	
	document.cookie= spot_clickedLoc + "=" +(cookieValue+1);
}

/**
 * 校验是否已经有过点击数据记录
 */
/*function checkCookie(clickedLoc)
{
	cookieValue=getCookie(clickedLoc);
    setCookie(clickedLoc,(cookieValue+1),null);
    

}*/